package com.tianji.jersey.filter;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AccessFilter implements Filter{
	private Log log = LogFactory.getLog(this.getClass());
	/* The FilterConfig of this filter */
	private FilterConfig filterConfig;
	private Properties ipProperties;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		log.debug("ip--->"+filterConfig.getInitParameter("ip1"));
//		String value = servletContext.getContext("ipconfig");
		String ip = request.getLocalAddr();
		String servername = request.getServerName();
		String scheame =((HttpServletRequest)request).getPathInfo();
		String url2 =((HttpServletRequest)request).getServletPath();
		String url3 =((HttpServletRequest)request).getRequestURL().toString();
		log.debug("url================="+url2);
		log.debug("url2================="+url3);
		boolean isAccess = ipProperties.containsValue(ip) || isJsonPService(request);
		log.debug("locssssal ip-----------"+ip+"---isaccess->"+isAccess);
		if(isAccess){
			filterChain.doFilter(request, response);
		}else{
			((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}
	private boolean isJsonPService(ServletRequest request){
		String url = request.getRemoteAddr();
		String url2 = request.getLocalAddr();
		log.debug("url================="+url);
		log.debug("url2================="+url2);
		return true;
	}
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		this.filterConfig = filterConfig;
		ServletContext servletContext = filterConfig.getServletContext();
		
		String value = servletContext.getInitParameter("ipconfig");
		InputStream is =servletContext.getResourceAsStream(value);
		
		Properties pro = new Properties();
		try {
			pro.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.ipProperties = pro;
	}
	
}
